package com.mrogrape.notepad.activity.action.item;

import java.awt.event.ActionEvent;

import javax.swing.Action;

import com.mrogrape.notepad.activity.action.NotepadAction;
import com.mrogrape.notepad.data.ViewContext;
import com.mrogrape.notepad.ui.editor.TextEditor;
import com.mrogrape.util.StringUtils;

public class InvertCaseMenuItemAction extends NotepadAction {

	/** serialVersionUID */
	private static final long serialVersionUID = -1L;

	public InvertCaseMenuItemAction(){

		super.putValue(Action.NAME, "Invert Case");
		super.putValue(Action.SHORT_DESCRIPTION, "Invert case of selected text.");
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		TextEditor editor = ViewContext.getMainFrame().getCurrentTextEditor();

		if(editor != null){

			String text = editor.getSelectedText();
			if(StringUtils.isEmpty(text)){
				return;
			}
			
			text = this.invertCase(text);
			editor.replaceSelection(text);
		}
	}
	
	private String invertCase(String text){
		
		StringBuilder sb = new StringBuilder();
		
		for(int i = 0; i < text.length(); i++){
			
			char c = text.charAt(i);
			if(Character.isUpperCase(c)){
				sb.append(Character.toLowerCase(c));
			}
			else{
				sb.append(Character.toUpperCase(c));
			}
		}
		return sb.toString();
	}
}
